package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    //新增菜品和对应口味  其中设计俩个表的操作dish表和口味表
    @Override
    //要么都成功要么都失败
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        //相关的属性拷贝过来，没有dto包含的口味
        BeanUtils.copyProperties(dishDTO, dish);

        //像菜品表插入1条数据
        dishMapper.insert(dish);
        //获取插入语句的主键值
        Long dishId = dish.getId();

        //向口味表插入x条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //这样插入数据
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    //菜品分页查询
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //开始分页查询 PageHelper使用插件
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
//total（总数）表示满足条件的所有数据总量.records（记录列表）表示当前页的数据集合
        long total = page.getTotal();
        List<DishVO> records = page.getResult();
        // 创建 PageResult 对象并传入 total 和 records
        PageResult pageResult = new PageResult(total, records);
        return pageResult;

    }

    //菜品批量删除
    //保证一组数据库操作的原子性，即这些操作要么全部成功完成并提交
    //要么遇到异常就全部撤销（回滚），以此来确保数据的一致性。
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否能够删除--是否在起售当中
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //当前菜品在起售中不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断当前菜品是否能够删除--当前菜品是否套餐关联了？如果关联了也不能删除
        List<Long> setmealids = setmealDishMapper.getSetmealByDishIds(ids);
        if (setmealids != null && setmealids.size() > 0) {
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除表中的菜品数据
//        for (Long id : ids) {
//            dishMapper.deleteById(id);
//            //同时菜品关联的口味数据
//            dishFlavorMapper.deleteById(id);
//
//        }
        //sql delete from dish where id in(?,?,?) 用动态删除的
        //根据菜品id集合批量删除菜品数据
        dishMapper.deleteByIds(ids);
        //根据菜品id集合批量删除关联的口味数据
        //sql delete from dish_flavor where dish_id in(?,?,?)
        dishFlavorMapper.deleteByIds(ids);


    }
    //根据id查询菜品和口味数据

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //根据id查询菜品数据
        Dish dish = dishMapper.getById(id);
        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        //将查询到的数据封装成vo
        DishVO dishVO = new DishVO();
        //除了口味和分类都拷贝过来
        BeanUtils.copyProperties(dish, dishVO);

        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    //修改菜品信息和口味信息
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //修改菜品的基本信息
        dishMapper.update(dish);

        //修改口味逻辑：1.删除原有的口味
        dishFlavorMapper.deleteById(dishDTO.getId());

        //2.插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //向口味表插入数据
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    //修改起售和禁售状态
    @Transactional
    @Override
    public void startOrStop(Integer status, Long id) {

        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);


        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)查出来套餐的id
            List<Long> setmealIds = setmealDishMapper.getSetmealByDishIds(dishIds);
            System.out.println("********************"+setmealIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {

                    Setmeal setmeal = new Setmeal();
                    setmeal.setStatus(status);
                    setmeal.setId(setmealId);
                    setmealMapper.update(setmeal);
                }
            }
        }

    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)

                .build();

        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


}
